package com.example.fegin.ribbon;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.Server;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;

/**
 * 自定义 负载均衡策略
 */

public class CunsumerRule extends AbstractLoadBalancerRule {

    private volatile int i = 1;

    public void initWithNiwsConfig(IClientConfig iClientConfig) {
    }

    public Server choose(Object o) {
        //获取所有可用服务
        List<Server> reachableServers = getLoadBalancer().getReachableServers();

        if (CollectionUtils.isEmpty(reachableServers)) {
            return null;
        }
        for (Server reachableServer : reachableServers) {
            int index = this.i % reachableServers.size();
            i++;
            if (i > 100000000) {
                i = 1;
            }
            //切换实例 打印日志  通过time 查看超时时间
            SimpleDateFormat simpleFormatter = new SimpleDateFormat("mm:ss");
            String format = simpleFormatter.format(new Date());
            System.out.println("CunsumerRule 切换实例 index:" + index + " i:" + i+" time:"+format);
            return reachableServers.get(index);
        }
        return null;
    }
}
